use base_data::channel::{Channel, CommandMsg, EndReason, OriginateMsg, OriginateWay};
use tools::{global_defin::config::global_config, ResultEx};
use tracing::debug;

use crate::config::business_config;

///应答呼入
#[inline]
pub fn answer(ch: &Channel) -> ResultEx<()> {
	debug!("向leg发送接通信号");
	Ok(ch.send(CommandMsg::AnswerCall(ch.id()))?)
}

///绑定通道
pub fn bridge_channel(ch: &Channel, peer_channel_id: u32) -> ResultEx<()> {
	debug!("接通两个通道,另一端id:{peer_channel_id}");
	Ok(ch.send(CommandMsg::BridgeChannel(peer_channel_id))?)
}

///发送180信号
pub fn ringing(ch: &Channel) -> ResultEx<()> {
	debug!("发送180.");
	Ok(ch.send(CommandMsg::Ringing)?)
}

///放指定的彩铃
pub fn play_sound_file_to_caller(ch: &Channel, path: &str) -> ResultEx<()> {
	if business_config().play_need_answer {
		answer(ch)?;
	}


	let file_path = format!("{}{}", global_config().play_bell_path, path);
	debug!("放指定彩铃,文件路径:{}", file_path);
	Ok(ch.send(CommandMsg::PlayBell(file_path))?)
}

///停止播放彩铃.目前就是直接断开,不管是否存在播放动作
pub fn stop_play_bell(ch: &Channel) -> ResultEx<()> {
	debug!("停止放彩铃");
	Ok(ch.send(CommandMsg::StopPlayBell)?)
}

///向sip发送挂断指定的通道.
pub fn kill_channel(ch: &Channel, reason: EndReason) -> ResultEx<()> {
	debug!("发送挂断指令,id:{},原因:{reason:?}",ch.id());
	Ok(ch.send(CommandMsg::HangupChannel(ch.id(), reason))?)
}

///向sip发送启动通话录音
pub fn record_sound(ch: &Channel, path: &str) -> ResultEx<()> {
	let path = format!("{}{}", global_config().rec_path, path);
	debug!("开始进行录音,路径:{path}");
	Ok(ch.send(CommandMsg::StartRecordSound(path.to_owned()))?)
}

///发起一个呼叫
pub fn originate(
	ch: &Channel,
	caller: &str,
	caller_name: &str,
	called: &str,
	way: OriginateWay,
) -> ResultEx<()> {
	let o = OriginateMsg {
		master_ch_id: ch.id(),
		caller_num: caller.to_owned(),
		called_num: called.to_owned(),
		caller_name: caller_name.to_owned(),
		way,
	};
	debug!("发起呼叫,信息:{:?}",o);

	Ok(ch.send(CommandMsg::Originate(o))?)
}
